﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace com.dz.ht.common
{
    public class NetSiteCatchManager
    {
        /// <summary>
        /// 页面超时时间
        /// </summary>
        const int c_TIME_OUT = 150000;

        /// <summary>
        /// 锁对象，防止线程并发
        /// </summary>
        static object m_ojb = new object();
        /// <summary>
        /// 读取页面内容
        /// </summary>
        /// <param name="i_url"></param>
        /// <param name="i_encoding"></param>
        /// <returns></returns>
        public static string ReadUrl(string i_url, Encoding i_encoding)
        {
            System.Threading.Thread.Sleep(200);
      

            Encoding t_encoding = null;
            string t_html = string.Empty;
            try
            {
                using (MemoryStream t_memory_stream = new MemoryStream())
                {
                    ReadPageCodeToStream(i_url, t_memory_stream, delegate(HttpWebResponse t_response)
                    {
                        t_encoding = i_encoding ?? GetEncoding(t_response);
                    });

                    t_memory_stream.Position = 0;//内存流复位以便于重新读取

                    using (StreamReader t_reader = new StreamReader(t_memory_stream, t_encoding))
                    {
                        t_html = t_reader.ReadToEnd();
                    }
                }
                if (!string.IsNullOrEmpty(t_html))
                {
                    t_html = t_html.Replace("\r", "").Replace("\n", "").Replace("\r\n", "");
                }
                return t_html;
            }
            catch (Exception ex)
            {

                LogHelper.Error("获取页面内容失败" + ex.ToString() + ",url=" + i_url);
                ex = null;
                return string.Empty;
            }
        }

        /// <summary>
        /// 获取页面编码
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        private static Encoding GetEncoding(HttpWebResponse response)
        {

            Encoding t_encoding = Encoding.Default;
            if (response.CharacterSet != null)
            {
                try
                {
                    t_encoding = Encoding.GetEncoding(response.CharacterSet);
                }
                catch (ArgumentException ex)
                {
                    LogHelper.Error("获取页面编码失败" + ex.ToString());
                }
            }
            return t_encoding;
        }

        /// <summary>
        /// 读取页面内容到数据流
        /// </summary>
        /// <param name="i_url"></param>
        /// <param name="i_stream"></param>
        /// <param name="ResponseCallback"></param>
        private static void ReadPageCodeToStream(string i_url, Stream i_stream, Action<HttpWebResponse> ResponseCallback)
        {
            HttpWebRequest t_request = (HttpWebRequest)WebRequest.Create(i_url);
            t_request.Timeout = c_TIME_OUT;
            t_request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5 (.NET CLR";
            t_request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
            t_request.Headers["Accept-Language"] = "en-us,en;q=0.5";
            t_request.Headers["Accept-Charset"] = "ISO-8859-1,utf-8;q=0.7,*;q=0.7";

            using (HttpWebResponse t_response = (HttpWebResponse)t_request.GetResponse())
            {
                if (ResponseCallback != null)
                {
                    ResponseCallback(t_response);
                }

                Stream t_stream = t_response.GetResponseStream();

                byte[] t_buffer = new byte[10000];
                int t_count = 0;
                while ((t_count = t_stream.Read(t_buffer, 0, t_buffer.Length)) != 0)
                {
                    i_stream.Write(t_buffer, 0, t_count);
                }
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="i_img_url"></param>
        public static int DownLoadImage(string i_img_url,long i_book_id)
        {
            lock (m_ojb)
            {
                WebClient t_web_client = new WebClient();
                string t_path = AppConfig.BookImgRoot;

                if (!Directory.Exists(t_path))
                {
                    Directory.CreateDirectory(t_path);
                }
                string t_file_name = Path.Combine(t_path, string.Format("{0}.jpg", i_book_id));
                try
                {
                    if (!File.Exists(t_file_name))
                    {
                        t_web_client.DownloadFile(i_img_url, t_file_name);
                       
                    }
                    return Consts.Success;
                    if (AppConfig.EnableBakUp)
                    {
                        string t_bak_path = AppConfig.BookImgRoot.TrimEnd('\\');
                        t_bak_path = t_bak_path.Substring(0, t_bak_path.LastIndexOf("\\"));
                        t_bak_path = Path.Combine(t_bak_path, "bookImgbak");
                        t_bak_path = Path.Combine(t_bak_path, DateTime.Now.ToString("yyyyMMdd"));

                        if (!Directory.Exists(t_bak_path))
                        {
                            Directory.CreateDirectory(t_bak_path);
                        }
                        string t_bak_file_name = Path.Combine(t_bak_path, string.Format("{0}.jpg", i_book_id));
                        if (!File.Exists(t_bak_file_name))
                        {
                            File.Copy(t_file_name, t_bak_file_name);
                        }
                    }
                    return Consts.Faild;
                }
                catch (Exception ex)
                {

                    LogHelper.Error("下载文件失败" + ex.ToString());
                    return Consts.Faild;
                }
            }
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="i_img_url"></param>
        /// <param name="i_file_name"></param>
        public static void DownLoadFile(string i_url, string i_file_name)
        {

            try
            {
                Uri u = new Uri(i_url);
                System.Net.HttpWebRequest mRequest = (HttpWebRequest)WebRequest.Create(u);
                mRequest.Method = "GET";
                mRequest.ContentType = "Application/octet-stream";
                HttpWebResponse wr = (HttpWebResponse)mRequest.GetResponse();


                Stream sIn = wr.GetResponseStream();
                FileStream fs = new FileStream(i_file_name, FileMode.Create, FileAccess.Write);
                long length = wr.ContentLength;
                int i = 0;
                long j = 0;

                byte[] buffer = new byte[1024];
                while ((i = sIn.Read(buffer, 0, buffer.Length)) > 0)
                {
                    j += i;
                    fs.Write(buffer, 0, i);


                }

                sIn.Close();
                wr.Close();

                fs.Close();

            }
            catch { }




        }

        /// <summary>
        /// 过滤字符
        /// </summary>
        /// <param name="i_text"></param>
        /// <returns></returns>
        public static string ReplaceContent(string i_text)
        {
            if (string.IsNullOrEmpty(i_text))
                return string.Empty;
            i_text = Regex.Replace(i_text, "<div.*?>.*?</div>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "<!--.*?-->", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "http.*?com", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "w.*?com", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "天天中文网", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = i_text.Replace("<a href=http://www.qidian.com>起点中文网 www.qidian.com 欢迎广大书友光临阅读，最新、最快、最火的连载作品尽在起点原创！</a>", "");
            i_text = Regex.Replace(i_text, "http.*?shouDa8.com", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "shouDa8.com", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "http.*?zcn.com", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "zcn.com", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = i_text.Replace("ahref=http://www.&gt;起点中文网www.欢迎广大书友光临阅读，最新、最快、最火的连载作品尽在起点原创！", "");
            i_text = Regex.Replace(i_text, "<a.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "</a>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "<script.*?>.*?</script>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);

            i_text = Regex.Replace(i_text, "<font.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "</font>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_text = Regex.Replace(i_text, "<div.*?>", "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            i_text = Regex.Replace(i_text, "</div>", "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            i_text = Regex.Replace(i_text, "<span.*?>", "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            i_text = Regex.Replace(i_text, "</span>", "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            i_text = Regex.Replace(i_text, "3Z中文网", "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            i_text = Regex.Replace(i_text, "四卷宝藏之谜", "", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            i_text = i_text.Replace("起点中文网  欢迎广大书友光临阅读，最新、最快、最火的连载作品尽在起点原创！", "");
            i_text = i_text.Replace("起点中文网欢迎广大书友光临阅读，最新、最快、最火的连载作品尽在起点原创！", "");
            i_text = i_text.Replace("起点中文网", "");
            i_text = i_text.Replace("尽在起点原创！", "");
            return i_text;
        }
    }
}
